<template>
    <nly-content-wrapper class="business content-warpper-2" :style="this.customerId?{'border':'none'}:{}">
        <div class="content-header-2">
            <!--按钮-->
            <div class="btn-wrapper clearfix" :style="this.customerId?{'border':'none','padding-top':'0','height':'52px' }:{}">
                <a-row class="text-center clearfix">
                    <a-col v-if="!this.customerId" :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="addBtnShow">
                            <div class="btns" @click="AddItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="editBtnShow">
                            <div class="btns" @click="EditItem()">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="disableBtnShow">
                            <div style="position:relative">
                                <div class="btns" @click="Disable">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>
                        <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="onShowSerch">
                                <a-icon class="btns-icon" type="file-search" />
                                <div class="btns-text">查询</div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="showMySet">
                                <a-icon class="btns-icon" type="setting" />
                                <div class="btns-text">自定义列</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="GetCustomizeList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">同步设置</div>
                            </div>
                    </a-col>
                    </a-col>
                    <a-col v-else style="text-align:left;line-height:52px;">
                        <a-button @click="AddItem" class="margin-left-10 margin-right-10" type="primary" ghost>
                            <a-icon type="file-add" theme="filled" />新增
                        </a-button>
                        <a-button @click="EditItem()" class="margin-right-10" type="primary" ghost>
                            <a-icon type="edit" theme="filled" />编辑
                        </a-button>
                        <a-button @click="Disable" class="margin-right-10" type="primary" ghost>
                            <a-icon type="delete" theme="filled" />删除
                        </a-button>
                        <!-- <a-button @click="onShowSerch" class="margin-right-10">
                            <a-icon type="file-search" />查询
                        </a-button> -->
                        <!-- <a-button @click="showMySet" class="margin-right-10">
                            <a-icon type="setting" />自定义列
                        </a-button> -->
                    </a-col>
                </a-row>
            </div>
            <!-- 查询方案 -->
            <a-col :span="24" v-if="!this.customerId">
                <div class="search-btn-box-gw">
                    <div class="item-small" ref="planLi">
                        <ul>
                            <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                            <li class="item-plan" :title="item.searchName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            <li class="item-plan" @click="onShowSerch">
                                <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                                自定查询
                                <a-icon class="icon-searh-btn" type="search" />
                            </li>
                        </ul>
                    </div>
                    <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                        <a-icon v-if="iconDirection" type="down" />
                        <a-icon v-else type="up" />
                    </div>
                </div>
            </a-col>
            <!-- 查询方案结束 -->

            <!-- <nly-row class="col-12">
                <nly-row class="col-12">
                    <fixed-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></fixed-condition>
                    <div class="mb-1">
                        <nly-button @click="showFunction" variant="info" button-class="mr-2"><i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />{{ show ? "折 叠" : "展 开" }}
                        </nly-button>
                        <nly-button variant="info" @click="onSerch" button-class="mr-2" :disabled="loading">查询</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="reset" :disabled="loading">重置</nly-button>
                        <nly-button variant="info" @click="showUsModal" button-class="mr-2">保存常用查询</nly-button>
                    </div>
                </nly-row>
            </nly-row>
            <dynamic-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);">
            </dynamic-condition> -->

            <a-drawer class="mySet" title="自定义列" width="520" height="300" @close="onMySetClose" :visible="mySetVisible">
                <a-checkbox-group v-model="mySetcheckedListLocal" :options="mySetplainOptions" @change="onMySetChange" />
                <nly-col xs="12" sm="12" class="form-inline align-self-start mt-3" style>
                    <nly-button-group>
                        <nly-button variant="danger" @click="onMySetClose" button-class="mr-2">关闭</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="saveMyShow">确定</nly-button>
                    </nly-button-group>
                </nly-col>
            </a-drawer>
            <nly-container fluid></nly-container>
        </div>
        <!-- 功能操作 -->
        <!-- <div>
            <a-button type="primary" class="crm-btn" @click="EditItem()" v-if="editBtnShow">编辑</a-button>
            <a-button type="primary" class="crm-btn" @click="Disable" v-if="disableBtnShow">删除</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="addBtnShow">新增</a-button>
            <i class="fa fa-fw fa-cog fieldSet " @click="showMySet"></i>
        </div> -->
        <nly-content>
            <!-- 列表 -->
            <a-table id="Business_tb" :columns="columns" :rowClassName="rowClassName" :data-source="data" :scroll="{ x: 500, y: 500 }" bordered :loading="loading" :pagination="pagination" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}">
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record,'business')" class="goToDetail">
                    {{record.crmName}}
                </a>
                <a slot="projectNo" slot-scope="text, record" @click="EditItem(record.id)" class="goToDetail">
                    {{record.projectNo}}
                </a>
                <a slot="businessTitle" slot-scope="text, record" @click="EditItem(record.id)" class="goToDetail">
                    {{text}}
                </a>
                <div slot="saleStage" slot-scope="text, record">
                    <a-tooltip :overlayStyle="{minWidth:'min-content'}" overlayClassName="step">
                        <template slot="title">
                            <div class="pl-3 pr-5 mt-4" style="display:flex;justify-content:space-between;">
                                <span style="font-weight:600;">客户名称：{{record.crmName}}</span>
                                <span class="ml-4" :style="goingStatusStyle.get(record.goingStatus)">
                                    状态：
                                    <a-tooltip :overlayStyle="{minWidth:'min-content'}" overlayClassName="step">
                                        <template slot="title" v-if="record.goingStatus == '输单' ">
                                            输单原因：{{record.goingStatus == '输单' ? record.loseReason : record.goingStatus}}
                                        </template>
                                        {{record.goingStatus}}
                                    </a-tooltip>
                                </span>
                            </div>
                            <a-steps :current="saleStageSteps.findIndex(f=>f == text)" style="min-width:800px" type="navigation" class="mb-4 mt-2" :status="(record.goingStatus == '输单' ? 'error' :'process')">
                                <a-step v-for="(item,index) in saleStageSteps" :key="index" :title="item">
                                    <a-icon slot="icon" type="smile-o" v-if="index == saleStageSteps.length - 1" />
                                </a-step>
                            </a-steps>
                        </template>
                        {{text}}
                    </a-tooltip>

                </div>
                <div slot="goingStatus" slot-scope="text, record">
                    <a-tooltip :overlayStyle="{minWidth:'min-content'}" overlayClassName="step">
                        <template slot="title" v-if="record.goingStatus == '输单' ">
                            输单原因：{{record.goingStatus == '输单' ? record.loseReason : record.goingStatus}}
                        </template>
                        {{text}}
                    </a-tooltip>
                </div>
                <a slot="activityId" slot-scope="text, record" @click="goToActivity(record)" class="goToDetail">{{record.activityName}}</a>
            </a-table>
            <!-- modal 弹窗  -->
            <drag-modal :visible="ModalVisible" :width="900" @cancel="hideModal" class="much-business-modal">
                <template slot="title">
                    <div style="display:flex;align-items: baseline;">
                        <span>{{formPostData.id ? '编辑商机管理' : '新增商机管理'}}</span>
                        <a-alert message="商机客户在线索公海，请领用/分配后修改" type="warning" show-icon class="ml-2" v-if="formPostData.id && !businessDetail.crmType" />
                    </div>
                </template>

                <nly-row class="form-inline zidongshifang">
                    <nly-col xs="12" sm="6" lg="6" style="margin-bottom:10px;">
                        <form-select title="客户名称" size="small" labelStyle="" rightClass="myRightClass" class="ml-1 mb-2" :required="true" :error="errors['formPostData.crmId']" :showSearch="true" :dataList="customerSelect" :handleSearch="delaySearch" :filterOption="false" v-model="formPostData.crmId" @input="inputLog" :valueTitle.sync="formPostData.crmName" :disabled="customerId">
                        </form-select>
                    </nly-col>
                    <nly-col xs="12" sm="6" lg="6" v-if="formPostData.id" style="margin-bottom:10px;">
                        <form-input title="商机编号" labelStyle="" rightClass="myRightClass" class="ml-1 mb-2" :required="false" :value="formPostData.projectNo" :readonly="true"></form-input>
                    </nly-col>
                    <nly-col xs="12" sm="6" lg="6" style="margin-bottom:10px;">
                        <form-show title="状态" showTooltip labelStyle="" rightClass="myRightClass" class="ml-1 mb-2" :value="formPostData.goingStatus">
                            <template slot="tooltip" v-if="formPostData.goingStatus == '输单' ">
                                <p class="pl-3 mt-4" style="font-weight:600;">输单原因：{{formPostData.goingStatus == '输单' ? formPostData.loseReason : formPostData.goingStatus}}</p>
                            </template>
                        </form-show>
                    </nly-col>
                </nly-row>

                <!-- 动态 表单  -->
                <dynamic-form :formPostData="formPostData" :initFormData="initFormData" :errors="formErrors" :isOk="isFromShow" :showSearch="ModalVisible" :showListStatus="false"></dynamic-form>

                <div class="saleStage mb-5 clearfix" :class="StatusBorder">
                    <div class="saleLeft clearfix">
                        <a-steps :current="currentStep" type="navigation" class="saleStageStep" @change="renderStep">
                            <a-step v-for="(item,index) in saleStageSteps" :key="index" :title="item" :status="(index == currentStep && formPostData.goingStatus == '输单') ? 'error' :''">
                                <!-- <a-icon slot="icon" type="loading" v-if="index == currentStep && formPostData.goingStatus == '正在进行'"/> -->
                                <a-icon slot="icon" type="smile-o" style="font-size:32px" v-if="index == saleStageSteps.length - 1" />
                            </a-step>
                        </a-steps>
                    </div>
                    <div class="saleRight clearfix">
                        <div v-show="isShowCloseBtn" class="ml-4">
                            <a-button type="danger" @click="like" class="mb-3" icon= "like" >赢单</a-button>
                            <a-button @click="dislike" icon= "dislike">输单</a-button>
                        </div>
                        <!-- <img :src="opneblue" title="点击关闭商机" @click="showReasonModal" v-show="isShowCloseBtn" class="ml-4" /> -->
                        <img :src="closered" title="点击开启商机" @click="openBusiness" v-show="!isShowCloseBtn" class="ml-4" />
                    </div>
                    <!-- <img :src="getImgUrl(props.i)" /> -->
                    <!-- <a-button type="danger" @click="showReasonModal" class="ml-4" v-show="isShowCloseBtn">关闭商机</a-button>
                        <a-button type="primary" @click="openBusiness" class="ml-4" v-show="!isShowCloseBtn">开启商机</a-button> -->
                    <!-- <a-dropdown >
                            <a-menu slot="overlay" @click="handleMenuClick" >
                            <a-menu-item v-for="(item,index) in saleStageSteps" :key="index">{{item}} </a-menu-item>
                            </a-menu>
                            <a-button type="primary" style="margin-left: 2rem;"> 选择阶段 <a-icon type="down" /> </a-button>
                        </a-dropdown> -->
                </div>
                <a-divider v-if="formPostData.id" orientation="left" style="margin:0px 0px 1rem 0px;">其他信息</a-divider>
                <a-row v-if="formPostData.id" class="form-inline row-cols-4 other-info not-border-form">
                    <a-col :span="24">
                        <form-input title="创建人" labelStyle="{width:100%;font-weight:normal}" rightClass="myRightClass" :value="formPostData.createUserName" :readonly="true"></form-input>
                    </a-col>
                    <a-col :span="24">
                        <form-input title="创建时间" labelStyle="{width:100%;font-weight:normal}" rightClass="myRightClass" :value="formPostData.createDate" :readonly="true"></form-input>
                    </a-col>
                    <a-col :span="24">
                        <form-input title="修改人" labelStyle="{width:100%;font-weight:normal}" rightClass="myRightClass" :value="formPostData.updateUserName" :readonly="true"></form-input>
                    </a-col>
                    <a-col :span="24">
                        <form-input title="修改时间" labelStyle="{width:100%;font-weight:normal}" rightClass="myRightClass" :value="formPostData.updateDate" :readonly="true"></form-input>
                    </a-col>
                </a-row>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="onSubmit" v-if="isEnableEdit">保存</a-button>
                    <a-button key="back" @click="hideModal">关闭</a-button>
                </template>
            </drag-modal>
            <a-modal title="请总结输单原因" :visible="isWinVisible" @ok="confirmLose" @cancel="hideWinModal">
                <!-- <a-radio-group v-model="isWin">
                    <a-radio value="赢单">赢单</a-radio>
                    <a-radio value="输单">输单</a-radio>
                </a-radio-group> -->
                <a-textarea title="输单原因" v-model="loseReason" class="form-control mt-3" style="width:100%;" placeholder="输单原因" />
            </a-modal>
            <!-- 常用查询名称编辑框 -->
            <a-modal title="保存常用查询" :visible="UsVisible" @ok="UserSearchSave" @cancel="hideUsModal">
                <nly-row class="form-inline">
                    <form-input title="名称" rightStyle="flex-grow:1;" class="ml-1 mb-1" style="flex:0.8;" :error="myUsErrors['userSearchEditItem.searchName']" :required="true" v-model="userSearchEditItem.searchName"></form-input>
                </nly-row>
            </a-modal>

            <!-- 查询方案弹窗 -->
            <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="cancel" width="1000px">
                <div class="content-box">
                    <div class="left-box">
                        <a-row class="btn-wrapper">
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?UserSearchSave():''">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                            <a-col :span="6">
                                <div class="btns" @click="showUsModal(2)">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">另存</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?showUsModal(1):''">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?onUserSearchDelete({key:planActive}):''">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                            </a-col>
                        </a-row>
                        <div class="plan-list">
                            <ul>
                                <li :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            </ul>
                        </div>
                    </div>
                    <div class="right-box">
                        <a-tabs default-activeKey="1" @change="callback">
                            <a-tab-pane key="1" tab="查询条件">
                                <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="conditions" :show="true" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                            </a-tab-pane>
                        </a-tabs>
                    </div>
                </div>
                <template slot="footer">
                    <div>
                        <!-- <div style="float:left">
                            <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                                下次以此方案进入
                            </a-checkbox>
                        </div> -->
                        <a-button type="primary" @click="onSerch">查询</a-button>
                        <a-button @click="cancel" class="margin-left-10">取消</a-button>
                    </div>
                </template>
                <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                    <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                    <template slot="footer">
                        <div>
                            <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                            <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                        </div>
                    </template>
                </a-modal>
            </a-modal>
            <drawerCrm :drawerVisible.sync="drawerVisible" :routeUrl="routeUrl" :title="drawerTitle" :dataItem="dataItem"></drawerCrm>

        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import opneblue from "@/assets/opneblue.png";
import closered from "@/assets/closered.png";
import { initValidator, checkAll } from "@/utils/validator/validator";
import { clearValue, clearKeys } from "@/utils/tool/object";
import getDate from "@/utils/tool/date";
import { Controlwidth } from "@/utils/antTableComponents";
import { save as SaveBusiness, PageList, disable, enable, detail } from "@/api/crm/business";
import { pageForSelect } from "@/api/crm/customer";

import dynamicList from "@/mixins/dynamicList";

import MiddleUtils from '@/utils/middle-utils'
let searchTimeout;
export default {
    mixins: [dynamicList],
    data () {

        //表格 头部 可伸缩
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            //gw 2021年8月16日11:04:08
            visibleSearchPlan: false,
            //gw 2021年8月16日11:04:16
            searchType: 5,        //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录  5.商机 
            source: "business",
            crmType: null,
            // crmType: '1,2',
            FixedConditionKeys: ["crmName", "saleStage"],  //固定的搜索条件的Key
            customRenderCode: ["crmName", "projectNo", "title", "saleStage", "goingStatus", "activityId"], //table 使用插槽的列
            RenderCodeChange: { title: "businessTitle" },
            requiredCode: ["goingStatus"],
            initFormDataExclude: ["saleStage"],           //表单排除的code（特殊处理，不归到自动生成表单里面）
            businessDetail: {},           //商机详情
            isWinVisible: false,           //是否赢单 编辑框是否显示
            isWin: "",                    //是否赢单 赢单、输单、无效
            loseReason: "",               //输单原因 
            goingStatusStyle: new Map(
                [
                    ['正在进行', 'color: #0b8235;'],
                    ['赢单', 'color: red;'],
                    ['输单', 'color: #1890ff;'],

                ]
            ),   //
            StepBoder: "process",            //
            opneblue,
            closered,
            //下拉搜索 客户条件
            selectPostData: {
                page: {
                    current: 1,
                    size: 1000
                },
                keyWord: '',
            },
            customerSelect: [],              //下拉搜索 客户
            route: this.$route.path,


            drawerVisible: false,//客户详情抽屉
            routeUrl: '',
            drawerTitle: '',
            dataItem: [],
            crmNameValue: null,
            rowClassName: (record, index) => {
                if (record.clickActive) {
                    return 'click-table-active'
                }
            },
        };
    },
    components: {
        drawerCrm: () => import('@/components/Crm/drawer')
    },
    beforeCreate: function () {
        // this.$options.components.drawerCrm = require('@/components/Crm/drawer').default
    },
    created () {
        const { formRules } = this;
        formRules["formPostData.crmId"] = { test: "required" };
    },
    updated () {
        Controlwidth("Business_tb", 50);
    },
    // components: {
    //     drawerCrm,//客户系统抽屉显示详情
    // },
    mounted () {
        MiddleUtils.$on('syncList', (value) => {
            if(this.$route.path == '/crm/business/list'){
                console.log("刷新syncList---商机");
                this.PageList();
            }
        })
    },
    watch: {
        "customerId": function (n, o) {
            console.log("watch_business_customerId:", n, o);
            const { basePostData } = this;
            basePostData.customerIds = n;
            this.reset();
            this.selectedKeys = [];
        },
        $route: {
            handler (nv, ov) {
                //离开路由关闭 右侧详情抽屉
                this.drawerVisible = false;
            },
            deep: true
        },
    },
    computed: {
        //销售阶段步骤 集合
        saleStageSteps: function () {
            const { onOffDefineFields } = this;
            let saleStage = onOffDefineFields.find(f => f.code == 'saleStage');
            if (saleStage) {
                let steps = saleStage.val.split(",");
                console.log("销售阶段插槽步骤集合", steps)
                if (steps.length < 2) {
                    this.$cerror({
                        title: '警告',
                        content: `请先配置销售阶段`,
                    });
                }
                return steps;
            }
            return [];
        },
        //计算属性--->当前步骤
        currentStep: function () {
            console.log("计算属性--->当前步骤")
            return this.saleStageSteps.findIndex(f => f == this.formPostData.saleStage);
        },
        //计算属性---> 根据 状态 改变 边框颜色
        StatusBorder: function () {
            const { goingStatus } = this.formPostData;
            switch (goingStatus) {
                case "正在进行": return "process"; break;
                case "赢单": return "win"; break;
                case "输单": return "lose"; break;
            }
        },
        //是否显示
        isShowCloseBtn: function () {
            const { formPostData } = this;
            return formPostData.goingStatus == "正在进行";
        },
        //是否显示 新增按钮 
        addBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:business:add")
                || (crmType == 0 && permissions.includes("crm:clue:business:add"))
                || (crmType == 1 && permissions.includes("crm:potential:business:add"))
                || (crmType == 2 && permissions.includes("crm:deals:business:add"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 编辑按钮 
        editBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:business:edit")
                || (crmType == 0 && permissions.includes("crm:clue:business:edit"))
                || (crmType == 1 && permissions.includes("crm:potential:business:edit"))
                || (crmType == 2 && permissions.includes("crm:deals:business:edit"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 删除按钮 
        disableBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:business:disable")
                || (crmType == 0 && permissions.includes("crm:clue:business:disable"))
                || (crmType == 1 && permissions.includes("crm:potential:business:disable"))
                || (crmType == 2 && permissions.includes("crm:deals:business:disable"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否可以编辑商机
        isEnableEdit: function () {
            const { formPostData, businessDetail } = this;
            if (formPostData.id && !businessDetail.crmType) {
                return false;
            } else {
                return true;
            }
        }
    },
    methods: {
        inputLog (e) {
            console.log("from_select input:", e, JSON.stringify(this.formPostData))
        },
        //跳转到 客户详情
        goToDetail (item, tabkey) {
            const { permissions } = this;
            if (!this.customerId && (permissions.includes("crm:potential:edit") || permissions.includes("crm:potential:edit") || permissions.includes("crm:deals:edit"))) {
                // this.$router.push(`/crm/customer/detail/${item.crmName}/${item.crmId}/${tabkey}`)

                this.drawerVisible = true;
                this.routeUrl = window.location.host + `/crm/customer/detail/${item.crmName}/${item.crmId}/${tabkey}`;
                this.drawerTitle = item.crmName;
                this.dataItem = item;
                this.$forceUpdate();
                //给点击的行一个颜色
                this.data.map(d => {
                    this.$set(d, 'clickActive', false)
                });
                this.$set(item, 'clickActive', true)

            }
        },
        //延迟 搜索
        delaySearch (value) {
            console.log("delaySearch...", value, searchTimeout);
            if (searchTimeout) {
                clearTimeout(searchTimeout);
                searchTimeout = null;
            }
            const go = () => { this.pageForSelect(value) }
            searchTimeout = setTimeout(go, 400);
        },
        //下拉搜索 客户
        pageForSelect (keyWord) {
            const { selectPostData } = this;
            Object.assign(selectPostData, { keyWord });
            selectPostData.crmTypes = [1, 2];//潜在客户
            pageForSelect(selectPostData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records } = data;
                    this.customerSelect = records;
                    console.log("搜索结果", records)
                }
            })
                .catch(error => { });
        },
        //添加
        AddItem () {
            this.selectPostData.keyWord = '';
            this.pageForSelect();
            const { formErrors, customer, userInfo, saleStageSteps } = this;
            const { crmName, id } = customer;
            let goingStatus = "正在进行";
            if (saleStageSteps.length == 0) {
                this.$error({
                    title: '提示',
                    content: '请配置销售阶段',
                });
                return false;
            }

            let saleStage = saleStageSteps[0];
            //获取当前时间
            let now = getDate.getCurrentMoment();
            let formPostData = {
                crmName,
                crmId: id,
                chargeManId: userInfo.id,
                chargeManName: userInfo.name,
                goingStatus, saleStage,
                getDate: now.format("YYYY-MM-DD"),
            }
            Object.assign(this, { formPostData });
            clearKeys(formErrors);
            this.isFromShow = true;
            this.ModalVisible = true;

            console.log("AddItem_formErrors->", formErrors)
        },
        //编辑
        EditItem (id) {
            const { selectedKeys, editBtnShow } = this;
            if (!editBtnShow) {
                return false;
            }
            if (!id) {
                let isOk = this.checkSingleSelectKey();
                if (!isOk) {
                    return false;
                }
                id = selectedKeys[0];
            }
            this.selectPostData.keyWord = '';
            this.pageForSelect();
            //查询详情
            detail({ id })
                .then(response => {
                    console.log("获取商机详情", response);
                    if (response.code === 200) {
                        const { data } = response;
                        // delete data.createDate;
                        // delete data.updateDate;
                        let formPostData = { ...data };
                        delete formPostData.status;
                        Object.assign(this, {
                            formPostData,
                            businessDetail: data
                        });
                        this.initCustomize();
                    }
                })
                .catch(error => { });
            this.isFromShow = true;
            this.ModalVisible = true;
        },
        onSerch () {
            const { postData } = this;
            postData.page.current = 1;
            this.PageList();
            this.cancel();
        },
        // 获取列表
        PageList () {
            const { postData, onOffDefineFields, customerId, customer } = this;
            // Object.assign(postData,{ customerIds: this.customerId})
            console.log("潜在客户——搜索条件：", onOffDefineFields, customerId, customer);
            postData.dtos = onOffDefineFields;
            if (customerId) {
                postData.crmType = customer.crmType;
            }
            this.loading = true;
            PageList(postData)
                .then(response => {
                    this.loading = false;
                    console.log("获取潜在客户列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        //转换自定义数据数据
                        this.defineFieldsAddToData(records);

                        this.data = records;
                        console.log("转换后的数据：records", records);
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        //
        handleMenuClick (e) {
            let current = e.key;
            this.renderStep(current);

        },
        //刷新 销售阶段 
        renderStep (current) {
            const { formPostData, saleStageSteps } = this;
            if (formPostData.goingStatus != "正在进行") {
                return false;
            }
            if(current == saleStageSteps.length - 1){
                this.like();
            }else{
                let goingStatus = "正在进行";
                Object.assign(formPostData, { saleStage: saleStageSteps[current], goingStatus });
            }
        },
        //开启商机
        openBusiness () {
            this.formPostData.goingStatus = "正在进行"
        },
        showReasonModal () {
            this.isWinVisible = true;
        },
        //赢单
        like(){
            const {  saleStageSteps } = this;
            let okText = "确定";
            let cancelText = "取消";
            let message = "是否确定‘赢单’";
            let _this = this;
            this.$confirm({
                title: '提示',
                content: <span>{message}</span>,
                okText,
                cancelText,
                onOk () {
                    let saleStage = saleStageSteps[saleStageSteps.length - 1];
                    Object.assign(_this.formPostData, { saleStage, goingStatus: "赢单", loseReason: null });
                    _this.onSubmit();
                },
                onCancel () {
                    return false;
                },
            });
        },
        //输单
        dislike(){
            const { saleStageSteps } = this;
            if(this.formPostData.saleStage == saleStageSteps[saleStageSteps.length - 1]){
                this.$error({
                    title: '提示',
                    content: '输单不能是最后一个阶段',
                });
                return false;
            }
           this.showReasonModal();
        },
        confirmLose(){
            const { loseReason ,saleStageSteps} = this;
            if(this.formPostData.saleStage == saleStageSteps[saleStageSteps.length - 1]){
                this.$error({
                    title: '提示',
                    content: '输单不能是最后一个阶段',
                });
                return false;
            }
            if (!loseReason) {
                    this.$error({
                        title: '提示',
                        content: '请填写输单原因',
                    });
                    return false;
            }
            Object.assign(this.formPostData, { goingStatus: "输单", loseReason });
            this.hideWinModal();
            this.onSubmit();
        },
        //确认 是否赢单
        confirmWinOrLose () {
            const { isWin, loseReason, saleStageSteps } = this;
            let saleStage = null;
            if (!isWin) {
                this.$error({
                    title: '提示',
                    content: '请选择选项',
                });
                return false;
            }
            if (isWin == "输单") {
                if (!loseReason) {
                    this.$error({
                        title: '提示',
                        content: '请填写输单原因',
                    });
                    return false;
                }
                if(this.formPostData.saleStage == saleStageSteps[saleStageSteps.length - 1]){
                    this.$error({
                        title: '提示',
                        content: '输单不能是最后一个阶段',
                    });
                    return false;
                }
                
                Object.assign(this.formPostData, { goingStatus: isWin, loseReason });
            } else if (isWin == "赢单") {
                saleStage = saleStageSteps[saleStageSteps.length - 1];
                Object.assign(this.formPostData, { saleStage, goingStatus: isWin, loseReason });
            }
            this.hideWinModal();
            this.onSubmit();
        },
        hideWinModal () {
            this.isWinVisible = false;
            this.isWin = "";
            this.loseReason = "";
        },
        //提交表单 1
        onSubmit () {
            const {
                formRules,
                formPostData,
                formErrors,
                saleStageSteps
            } = this;
            if(this.formPostData.saleStage == saleStageSteps[saleStageSteps.length - 1] && this.formPostData.goingStatus == '正在进行'){
                this.$error({
                    title: '提示',
                    content: '"正在进行"不能是最后一个阶段',
                });
                return false;
            }
            //全部校验一次
            checkAll(this, formRules, formPostData, formErrors);
            if (Object.keys(formErrors).length > 0) {
                this.isFromShow = false;
                this.$nextTick(function () {
                    this.isFromShow = true;
                });
                return false;
            }
            this.SaveBusiness();
        },
        //提交表单 2
        SaveBusiness () {
            const {
                formPostData,
                onOffDefineFields,
            } = this;
            //自定义字段 重组
            let defineFieldsSets = onOffDefineFields.filter(f => f.dataType == 2);
            let defineFields = {};
            //获取重组后的自定义集合
            this.getDefineFields(defineFields, formPostData, defineFieldsSets);
            Object.assign(formPostData, {
                defineFields: JSON.stringify(defineFields)
            });
            let _this = this;
            SaveBusiness(formPostData)
                .then(response => {
                    console.log("SaveCustomer_response.code", response.code);
                    if (response.code === 200) {
                        _this.$message.success("保存成功");
                        _this.hideModal();
                        if (_this.customerId) {
                          MiddleUtils.$emit('syncList');
                        }
                         _this.PageList();
                    }
                })
        },
        //删除商机
        Disable () {
            const { selectedKeys } = this;
            let isOk = this.checkSingleSelectKey(true);
            if (!isOk) {
                return false;
            }
            let _this = this;
            let ids = selectedKeys;
            this.$confirm({
                title: '确认',
                content: '您确定要删除该商机吗？',
                onOk () {
                    disable(ids)
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                _this.PageList();
                                _this.selectedKeys = [];
                            }
                        })
                },
                onCancel () { },
            });
        },
        //
        goToActivity (record) {
            const { permissions } = this;
            if (permissions.includes("crm:activity:add") || permissions.includes("crm:activity:edit")) {
                this.$router.push({ path: "/crm/activity/list", query: { id: record.activityId } })
            }
        },
        //gw 2021年8月16日11:51:51
        cancel () {
            //置空临时查询条件
            // if (this.planActive == 0) {
            //     setTimeout(() => {
            //         this.onOffDefineFields.forEach(item => {
            //             item.value = '';
            //         });
            //     }, 200)
            // }
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
    },
};
</script>
<style lang="less">
    .step {
        display: -ms-grid;
        .ant-tooltip-content {
            padding: 0 !important;
            box-shadow: 0 0 10px #40a9ff;
            .ant-tooltip-inner {
                color: rgba(0, 0, 0, 0.75) !important;
                background-color: #fff !important;
            }
        }
    }

    //正在进行 边框颜色
    .process {
        border: 2px solid #0c0 !important;
    }
    .lose {
        border: 2px solid #40a9ff !important;
    }
    .win {
        border: 2px solid rgb(255, 0, 0) !important;
    }
    .saleStage {
        // display: flex;
        margin-top: 30px;
        align-items: center;
        border: 1px solid;
        padding: 30px 20px;
        .saleLeft {
            width: 700px;
            height: auto;
            float: left;
            padding-top: 10px;
            .ant-steps-item {
                float: left;
                width: 126px;
                flex: none;
                margin-bottom: 10px;
            }
            .ant-steps-item-title {
                width: 64px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                text-align: center;
            }

            .ant-steps {
                display: block;
            }
        }
        .saleRight {
            float: left;
            width: 100px;
            height: auto;
        }
    }
    @import '~@/style/crm.less';
    .much-business-modal {
        .ant-select-selection__rendered,
        .ant-select-selection-selected-value,
        .ant-select-selection {
            height: 32px !important;
            line-height: 32px !important;
        }

        .ant-select-sm,
        .ant-input-sm,
        .ant-input-number,
        .ant-input-number-input {
            height: 32px !important;
        }
    }
    // .zidongshifang {
    //     .ant-select-selection__rendered,
    //     .ant-select-selection-selected-value,
    //     .ant-select-selection {
    //         height: 30px !important;
    //         line-height: 30px !important;
    //     }
    // }
    .not-border-form {
        .ant-input {
            border: none;
        }
    }
</style>
